(function (w) {
    var c = {};
    c.data = {};
    c.init = function () {
        var cartData = {};
        mcake.api.get('5e49d89248023811', {cityId: util.cookie.get('cityId'), uid: util.cookie.get('user_uid')}, null, function (ret) {
            cartData = ret.data;
        });
        this.data = cartData;
        this.load.init();
    };
    c.load = {
        isFitOrRmd: false,
        init: function () {
            //if (mcake.user.isLogin) {
                this.list();
                if (!this.isFitOrRmd) {
                    this.FitOrRmd();
                }
           // }
            this.topCart();
            this.selectEvent();
        },
        selectEvent:function(){
            $(".selectWrap").each(function(){
                var self = $(this);
                $(this).find(".select-box").click(function(){
                    $(".select").fadeOut();
                    self.find(".select-box").addClass("up");
                    self.find(".select").stop().fadeIn();
                    self.find(".text").fadeIn(0);
                    self.find(".action-input-container").fadeOut(0);
                    return false;
                });
                $(this).find(".select li").not(".card_by_self").click(function(){
                    $(this).addClass("cur").siblings().removeClass("cur");
                    self.find(".select-box").removeClass("up");
                    self.find(".select").fadeOut();
                    var type = parseInt($(this).attr('data-type'));
                    var text = $(this).text();
                    if (text == self.find(".select-box").find('p').text()) {
                        return false;
                    }
                    switch (type) {
                        case 1: // 閫夋嫨纾呮暟
                            var id = $(this).attr('data-id');
                            var sid = $(this).attr('data-sid');
                            var num = $(this).attr('data-num');
                            mcake.api.post('b34ce2c4f51281f9', {id: id, sid: sid, num: num, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {
                                if (ret.code == 1) {
                                    self.find(".select-box").find('p').text(text);
                                    cart.data = ret.data;
                                    cart.load.init();
                                } else {
                                    mcake.msg.error(ret.msg);
                                }
                            });
                            break;
                        case 2: // 閫夋嫨鐢熸棩鐗�
                            var bdCard = $(this).text();
                            var isbdcard = 1;
                            if (bdCard == '涓嶉渶瑕�') {
                                bdCard = '';
                                isbdcard = 0;
                            }
                            if (util.str.length(bdCard) > 18) {
                                mcake.msg.error('宸у厠鍔涚敓鏃ョ墝闄�9涓眽瀛楁垨18涓瓧绗�');
                                return false;
                            }
                            var key = $(this).attr('data-key');
                            var goods_key = $(this).attr('data-id');
                            mcake.api.post('48862e25f3cfbaa8', {key: key, goods_key: goods_key, content: bdCard, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, '', function (ret) {
                                if (ret.code == 1) {
                                    self.find(".select-box").find('p').text(text);
                                    self.find(".inpt").val('');
                                    cart.data.goods[key].isbdcard = isbdcard;
                                    mcake.msg.success(ret.msg);
                                } else {
                                    mcake.msg.error(ret.msg);
                                }
                            });
                            break;
                        case 3: // 閫夋嫨铚＄儧
                            var goods_key = $(this).attr('data-id');
                            var key = $(this).attr('data-key');
                            var num = 1;
                            if (text == '涓嶉渶瑕�') {
                                num = 0;
                            }
                            mcake.api.post('3350a5acc86b2164', {id: 53, key: key, goods_key: goods_key, num: num, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, '', function (ret) {
                                if (ret.code == 1) {
                                    self.find(".select-box").find('p').text(text);
                                    cart.data.goods[key].iscandle = num;
                                    mcake.msg.success(ret.msg);
                                } else {
                                    mcake.msg.error(ret.msg);
                                }
                            });
                            break;
                    }
                    return false;
                });
                $(this).find(".inpt").click(function(){
                    return false;
                });

                $(this).find(".card_by_self").click(function(){
                    self.find(".select-box").removeClass("up");
                    self.find(".select").fadeOut();
                    self.find(".text").fadeOut(0);
                    self.find(".action-input-container").fadeIn(0);
                    self.find(".inpt").focus();
                    return false;
                });

                $(this).find(".birth-card-btn").click(function(){
                    var bdCard = self.find(".inpt").val();
                    if (bdCard.trim() == '') {
                        mcake.msg.error('宸у厠鍔涚敓鏃ョ墝涓嶈兘涓虹┖');
                        return false;
                    }
                    if (util.str.length(bdCard) > 18) {
                        mcake.msg.error('宸у厠鍔涚敓鏃ョ墝闄�9涓眽瀛楁垨18涓瓧绗�');
                        return false;
                    }
                    if (c.load.checkBdCard(bdCard)) {
                        mcake.msg.error('宸у厠鍔涚敓鏃ョ墝涓嶈兘瀛樺湪琛ㄦ儏鎴栫壒娈婄鍙�');
                        return false;
                    }
                    self.find(".select-box").removeClass("up");
                    self.find(".select").fadeOut();
                    self.find(".text").fadeIn(0);
                    self.find(".action-input-container").fadeOut(0);
                    var key = $(this).attr('data-key');
                    var goods_key = $(this).attr('data-id');
                    mcake.api.post('48862e25f3cfbaa8', {key: key, goods_key: goods_key, content: bdCard, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, '', function (ret) {
                        if (ret.code == 1) {
                            self.find(".select-box").find('p').text(bdCard);
                            self.find(".card_by_self").addClass("cur").siblings().removeClass("cur");
                            cart.data.goods[key].isbdcard = 1;
                            mcake.msg.success(ret.msg);
                        } else {
                            mcake.msg.error(ret.msg);
                        }
                    });
                    return false;
                });
            });

            $(document).click(function(){
                $(".select-box").removeClass("up");
                $(".select").fadeOut();
            });
        },
        checkBdCard: function (substring) {
            for (var i = 0; i < substring.length; i++) {
                var hs = substring.charCodeAt(i);
                if (0x2100 <= hs && hs <= 0x27ff) {
                    return true;
                } else if (0x2B05 <= hs && hs <= 0x2b07) {
                    return true;
                } else if (0x2934 <= hs && hs <= 0x2935) {
                    return true;
                } else if (0x3297 <= hs && hs <= 0x3299) {
                    return true;
                } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                    return true;
                }
            }
            var regExs=[/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g,/([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g];
            for (var index = 0; index < regExs.length; index++) {
                if (regExs[index].test(substring)) {
                    return true;
                }
            }
            return false;
        },
        list: function () {
            if (c.data.master.goodsNum > 0 && config.controller === 'Cart' && config.action === 'index') {
                this.dataResult();
                // 璐墿杞︽湁鍟嗗搧
                $('#cart-app').html('');
                $('#cart-content-tmpl').tmpl(c.data).appendTo('#cart-app');
                c.event.toggle();
                c.event.add();
                c.event.mod();
                c.event.dec();
                c.event.select();
               // c.event.del();
                c.event.selectAll();
                c.event.showGift();
                c.event.pay();
            } else if (c.data.master.goodsNum === 0 && config.controller === 'Cart' && config.action === 'index') {

                // 璐墿杞︽病鏈夊晢鍝�
                $('#cart-app').html('');
                $('#cart-empty-tmpl').tmpl(c.data).appendTo('#cart-app');
            }
        },
        FitOrRmd: function () {
            /**鍔犺浇鍔犺喘閰嶄欢**/
            if (config.controller === 'Cart') {
                if (c.data.master.goodsNum === 0) {
                    mcake.api.get('56eee250c2cf6487', {
                        cityId: util.cookie.get('cityId'),
                        page: 1,
                        bid: 5,
                        size: 10
                    }, '', function (ret) {
                        switch (ret.code) {
                            case 1:
                                var data = {};
                                data.title = '涓烘偍鎺ㄨ崘';
                                data.list = ret.data;
                                $('.recommendForYou').html('');
                                $('#recommendForYou-tmpl').tmpl(data).appendTo('.recommendForYou');
                                if (window.head) {
                                    head.event.addToCart();
                                }
                                break;
                            default:


                        }
                    });
                } else {
                    mcake.api.get('0434b49d1ac28f9d', {
                        cityId: util.cookie.get('cityId'),
                        page: 1,
                        bid: 5,
                        size: 10
                    }, '', function (ret) {
                        switch (ret.code) {
                            case 1:
                                var data = {};
                                data.title = '鍔犺喘閰嶄欢';
                                data.list = ret.data.list;
                                $('.recommendForYou').html('');
                                $('.mycart-box .recommendForYou').eq(0).html('');
                                $('#recommendForYou-tmpl').tmpl(data).appendTo('.mycart-box .recommendForYou');
                                if (window.head) {
                                    head.event.addToCart();
                                }
                                var w = 160.5 + 40;
                                if ($(window).width() < 1400) {
                                    w = 160.5 + 30;
                                }
                                var listWidth = w * ret.data.list.length;
                                $('.item-list').css({width: listWidth+'px'});
                                break;
                            default:
                        }
                    });
                }
            }
        },
        dataResult: function () {
            // 鏁版嵁澶勭悊
            $.each(c.data.goods, function (i, v) {
                // 閰嶄欢
                var fit = '';
                $.each(v.fittings, function (ifa, vf) {
                    if (parseInt(vf.id) === 51) {
                        fit += '鍚�' + vf.num + vf.uname + vf.name +  '锛堟瘡濂椾竴涓鐩橈紝涓€鎶婇鍕猴級';
                    } else if (parseInt(vf.id) === 57) {
                        fit += '鍚�' + vf.num + vf.uname + vf.name;
                    }
                });
                v.fit = fit;
                delete fit;

                // 瑙勬牸
                for (var j = 0; j < v.list.length; j++) {
                    if (v.id === v.list[j].id) {
                        v.edible = v.list[j].edible;
                        break;
                    }
                }
                v.data = util.Base64.encode(JSON.stringify(v));
            });
        },
        topCart: function () {
            if (typeof c.data.master !== 'undefined') {
                this.dataResult();
                $('#top-car-box').html('');
                // 澶撮儴璐墿杞︽ā鏉挎覆鏌�
                $('#top-car-box-tmpl').tmpl(c.data).appendTo('#top-car-box');
                c.event.del();
                $('.mycar-num').text(c.data.master.goodsNum);
            } else {
                $('.mycar-num').text(0);
            }
            head.event.goCart();
            head.event.goBuy();
        }
    };
    c.event = {
        toggle: function () {
            $('.icon09')
                .click(function () {
                    var data = JSON.parse(util.Base64.decode($(this).parent().siblings('[data-data]').data('data')));
                    var buy = $(this).data('buy');
                    switch (buy) {
                        case 0:
                            mcake.api.post('b2d339c92168c794', {id: data.key, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {
                                switch (ret.code) {
                                    case 1:
                                        mcake.msg.success('鍕鹃€夊晢鍝佹垚鍔�');
                                        cart.data = ret.data;
                                        cart.load.init();
                                        break;
                                    default:
                                        break;
                                }
                            });
                            break;
                        case 1:
                            mcake.api.post('07399bea14647979', {id: data.key, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {

                                switch (ret.code) {
                                    case 1:
                                        mcake.msg.success('鍙栨秷鍟嗗搧鎴愬姛');
                                        cart.data = ret.data;
                                        cart.load.init();
                                        break;
                                    default:
                                        break;
                                }
                            });
                            break;
                    }
                    $(this).toggleClass('icon10');
                });
        },
        add: function () {
            $('.cart-num .add')
                .click(function () {
                    var self = $(this);
                    var data = JSON.parse(util.Base64.decode(self.parent().siblings('[data-data]').data('data')));
                    var num = parseInt(self.prev().val()) + 1;
                    if (num >= 51) {
                        return;
                    }
                    mcake.api.post('b34ce2c4f51281f9', {id: data.key, sid: data.id, num: num, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {

                        switch (ret.code) {
                            case 1:
                                // mcake.msg.success('淇敼鍟嗗搧鎴愬姛');
                                cart.data = ret.data;
                                cart.load.init();
                                break;
                            default:
                                mcake.msg.error(ret.msg);
                                break;
                        }
                    });
                });
        },
        select: function () {
            $('.cart-kind .pond').click(function () {
                var html = '';
                var self = $(this);
                var data = JSON.parse(util.Base64.decode(self.parent().siblings('[data-data]').data('data')));
                for (var i = 0; i < data.list.length; i++) {
                    html += '<p ' + (data.list[i].id === data.id ? 'class="cur"' : '') + ' data-id=' + data.list[i].id + '>' + data.list[i].spec + (data.list[i].weight ? (' 鈥斺€� ' + data.list[i].weight) : '') + '</p>';
                }
                $(this).siblings('.pond-pick').html(html);
                c.event.selected();
                $(this).siblings('.pond-pick').show();
                $('.gg').show()
            });

            $('.gg').click(function () {
                $('.pond-pick,.gg').hide()
            })
        },
        selected: function () {
            $('.cart-kind .pond-pick p').click(function () {
                var self = $(this);
                var data = JSON.parse(util.Base64.decode(self.parent().parent().siblings('[data-data]').data('data')));
                var num = parseInt(self.parent().parent().siblings('.cart-num').find('.my-num').val()) - 0;
                var id = $(this).data('id');
                if (id === data.id) {
                    return false;
                }
                if (num <= 0) {
                    return;
                }
                mcake.api.post('b34ce2c4f51281f9', {id: data.key, sid: id, num: num, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {
                    switch (ret.code) {
                        case 1:
                            // mcake.msg.success('淇敼鍟嗗搧鎴愬姛');
                            cart.data = ret.data;
                            cart.load.init();
                            break;
                        default:
                            mcake.msg.error(ret.msg);
                            break;
                    }
                });
                $('.cart-kind .pond-pick,.gg').hide();
            })
        },
        dec: function () {
            $('.cart-num .dec')
                .click(function () {
                    var self = $(this);
                    var data = JSON.parse(util.Base64.decode(self.parent().siblings('[data-data]').data('data')));
                    var num = parseInt(self.next().val()) - 1;
                    if (num <= 0) {
                        return;
                    }
                    mcake.api.post('b34ce2c4f51281f9', {id: data.key, sid: data.id, num: num, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {
                        switch (ret.code) {
                            case 1:
                                // mcake.msg.success('淇敼鍟嗗搧鎴愬姛');
                                cart.data = ret.data;
                                cart.load.init();
                                break;
                            default:
                                mcake.msg.error(ret.msg);
                                break;
                        }
                    });
                });
        },
        mod: function () {
            $('[name=my-num]').blur(function () {
                var num = parseInt($(this).val());
                if (isNaN(num) || num === 0) {
                    num = 1;
                } else if (num > 50) {
                    num = 50;
                }
                $(this).val(num);
                var goods = JSON.parse(util.Base64.decode($(this).parent().siblings('[data-data]').data('data')));
                mcake.api.post('b34ce2c4f51281f9', {id: goods.key, sid: goods.id, num: num, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {
                    switch (ret.code) {
                        case 1:
                            // mcake.msg.success('淇敼鍟嗗搧鎴愬姛');
                            cart.data = ret.data;
                            cart.load.init();
                            break;
                        default:
                            mcake.msg.error(ret.msg);
                            break;
                    }
                });
            });
        },
        del: function () {
            $('.del,.del-icon')
                .click(function () {
                    var data = JSON.parse(util.Base64.decode($(this).parent().siblings('[data-data]').data('data')));

                    mcake.api.post('c5cc50070b5c48db', {id: data.key, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {
                        switch (ret.code) {
                            case 1:
                                mcake.msg.success('鍒犻櫎鍟嗗搧鎴愬姛');
                                cart.data = ret.data;
                                cart.load.init();
                                break;
                            default:
                                mcake.msg.error('鍒犻櫎鍟嗗搧澶辫触');
                                break;
                        }
                    });

                });
        },
        selectAll: function () {
            $('.pay-img')
                .click(function () {
                    $(this)
                        .toggleClass('icon11');
                    if (cart.data.master.goodsNum > 0) {
                        var ids = '';
                        $.each(cart.data.goods, function (i, v) {
                            ids += v.key + ',';
                        });
                        if (cart.data.master.goodsNum > 0 && cart.data.master.num !== cart.data.master.goodsNum) {
                            mcake.api.post('b2d339c92168c794', {id: ids, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {
                                switch (ret.code) {
                                    case 1:
                                        mcake.msg.success('鍕鹃€夊晢鍝佹垚鍔�');
                                        cart.data = ret.data;
                                        cart.load.init();
                                        break;
                                    default:
                                        break;
                                }
                            });
                        } else {
                            mcake.api.post('07399bea14647979', {id: ids, cityId: util.cookie.get('cityId'), uid: mcake.user._uid}, null, function (ret) {

                                switch (ret.code) {
                                    case 1:
                                        mcake.msg.success('鍙栨秷鍟嗗搧鎴愬姛');
                                        cart.data = ret.data;
                                        cart.load.init();
                                        break;
                                    default:
                                        break;
                                }
                            });
                        }
                    }
                });
        },
        pay: function () {
            $('.pay-buy').click(function () {
                if (cart.data.master.num === 0) {
                    mcake.msg.error('璇峰嬀閫夊晢鍝�');
                    return;
                }
                var product_name = '';
                var order_amount = 0;
                var product_amount = 0;
                // 妫€鏌ユ槸鍚﹀嬀閫夌敓鏃ョ墝
                 var bdcardError = 0;
                // 妫€鏌ユ槸鍚﹀嬀閫夎湣鐑�
                 var candleError = 0;
                 $.each(cart.data.goods, function (k, v) {
                     var havetableware = false;
                     if (v.buy == 1 && v.fittings && v.fittings[53]) {
                         havetableware = true;
                     }
                     if (v.bcid == 1 && havetableware && v.isbdcard == -1) {
                         bdcardError++;
                     }
                     if (v.bcid == 1 && havetableware && v.iscandle == -1) {
                         candleError++;
                     }
                     if (v.buy == 1) {
                         product_name += v.name + ' ';
                         order_amount += parseFloat(v.pprice);
                         product_amount += parseFloat(v.salePrice);
                     }
                 });
                 if (bdcardError > 0) return mcake.msg.error('璇烽€夋嫨鏄惁闇€瑕佸阀鍏嬪姏鐢熸棩鐗�');
                 if (candleError > 0) return mcake.msg.error('璇烽€夋嫨鏄惁闇€瑕佽湣鐑�');

                _hmt.push(['_trackCustomEvent', 'pay', {
                        "order_amount": order_amount,
                        "product_amount": product_amount,
                        "product_amount_paid": order_amount,
                        "product_name": product_name
                    }
                ]);

                // 缁撶畻鍓嶆鏌�
                mcake.api.get('5f4571fa45faf2c9', {cityId: util.cookie.get('cityId')}, '', function (ret) {
                    if (ret.code == 1) {
                        window.location.href = '/order/checkout';
                    } else {
                        mcake.msg.error(ret.msg);
                    }
                });
            });
        },
        showGift: function () {
            $('.master .s-3').click(function () {
                $(this).parent().siblings('.change-good-promotion').show();
                $(this).parent().parent().siblings().find('.change-good-promotion').hide();
                $('.bg-promotion').show();
                $('.bg-promotion').click(function () {
                    $('.change-good-promotion').hide();
                    $('.bg-promotion').hide();
                });
            });
            $('.change-good-promotion .good-p').click(function () {
                var key = $(this).data('key');
                var id = $(this).data('id');
                mcake.api.post('0a6d537111878419', {key: key, pid: id}, '', function (ret) {
                    switch (ret.code) {
                        case 1:
                            c.data = ret.data;
                            c.load.init();
                            $('.bg-promotion').hide();
                            break;
                        default:
                            mcake.msg.error(ret.msg);

                    }

                });
            });
            $('.a2').click(function () {
                var data = {};
                data.pid = $(this).data('id');
                data.ptype = $(this).data('ptype');
                data.cityId = util.cookie.get('cityId');
                var key = $(this).data('key');
                if (typeof key !== 'undefined') {
                    data.key = key.toString();
                }

                mcake.api.get('7375baac25c217c2', data, '', function (ret) {
                    switch (ret.code) {
                        case 1:
                            ret.data.pid = data.pid;
                            ret.data.ptype = data.ptype;
                            ret.data.key = data.key ? data.key : '';
                            $('#gift-box').html('');
                            $('#gift-box-tmpl').tmpl(ret.data).appendTo('#gift-box');
                            $('.gift-box,.bg').show();
                            break;
                        default:

                    }

                });

                $('.good-p').click(function () {
                    $('.change-good').hide();
                });
                $('.gift-box .dec').click(function () {
                    var num = parseInt($(this).siblings('.num').text());
                    num--;
                    if (num <= 1) {
                        $(this).removeClass('on');
                    }
                    if (num < 1) {
                        return false;
                    }
                    $(this).siblings('.add').addClass('on');
                    $(this).siblings('.num').html(num);
                });

                $('.gift-box .add').click(function () {
                    var stock = $(this).data('stock');
                    var num = parseInt($(this).siblings('.num').text());
                    num++;
                    if(num >= stock){
                        $(this).removeClass('on');
                    }
                    if (num > stock) {
                        return false;
                    }
                    $(this).siblings('.dec').addClass('on');
                    $(this).siblings('.num').text(num);
                });

                // 鍕鹃€夋崲璐晢鍝�
                $('.choose-gift').click(function () {

                    if ($(this).hasClass('selected')) {
                        $(this).siblings().find('.num').data('num', 0);
                    } else {
                        $(this).siblings().find('.num').data('num', 1);
                    }

                    $(this).toggleClass('selected');
                });

                // 鎻愪氦鎹㈣喘鍟嗗搧
                $('.gift-btn').click(function () {
                    var post = {};
                    var ids = '';
                    var nums = '';
                    var pid = $('.gift-box').data('pid');
                    if (pid) {
                        post.pid = pid;
                    }
                    post.ptype = $('.gift-box').data('ptype');
                    post.cityId = util.cookie.get('cityId');
                    var key = $('.gift-box').data('key');
                    if (typeof key !== undefined) {
                        post.key = key;
                    }

                    $('.gift-box .mid-box .choose-gift').each(function (i, v) {
                        var data = JSON.parse(util.Base64.decode($(this).parent().data('data')));
                        ids += data.id + ',';
                        if ($(this).hasClass('selected')){
                            nums += parseInt($(this).siblings().find('.num').html()) + ',';
                        } else {
                            nums += '0,';
                        }
                    });
                    if (ids != '') {
                        post.id = ids.slice(0, ids.length - 1);
                        post.num = nums.slice(0, nums.length - 1);
                        mcake.api.post('a88729ee8b2e7b9f', post, null, function (ret) {
                            switch (ret.code) {
                                case 1:
                                    $('.gift-box,.bg').hide();
                                    c.data = ret.data;
                                    c.load.init();
                                    break;
                                default:
                                    mcake.msg.error(ret.msg);

                            }
                        });
                    } else {
                        $('.gift-box,.bg').hide();
                    }

                });
                $('.bg,.x').click(function () {
                    $('.gift-box,.bg').hide();
                });

            });
        }
    };
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = c;
    } else if (typeof exports !== 'undefined') {
        exports.cart = c;
    } else if (typeof define === 'function' && define.amd) {
        define([], function () {
            return c;
        });
    } else if (typeof w.cart === 'undefined') {
        w.cart = c;
    }
})(window);
cart.init();